package com.kasax.ipcbus.corel.marker;

import com.kasax.ipcbus.bean.RequestBean;
import com.kasax.ipcbus.bean.RequestParameter;
import com.kasax.ipcbus.utils.LogUtils;
import com.kasax.ipcbus.utils.TypeUtils;

import java.lang.reflect.Method;

/**
 * 单例构建
 */
public class InstanceResponseMaker extends ResponseMaker {
    private Method mMethod;

    @Override
    protected Object invokeMethod() {
        Object obj = null;
        try {
            obj = mMethod.invoke(null, mParameters);
            LogUtils.i(getClass(), "invokeMethod obj: " + obj);
            // 缓存对象
            OBJ_CENTER.putObject(obj.getClass().getName(), obj);
        } catch (Exception e) {
            LogUtils.e(getClass(), e);
        }
        return null;
    }

    @Override
    protected void setMethod(RequestBean requestBean) {
        // 解析参数：getInstance可能会带参数
        RequestParameter[] parameters = requestBean.getRequestParameters();
        Class<?>[] paramTypes = null;
        if (parameters != null && parameters.length > 0) {
            paramTypes = new Class[parameters.length];
            for (int i = 0; i < parameters.length; ++i) {
                paramTypes[i] = typeCenter.getClassType(parameters[i].getParamClsName());
            }
        }

        // 方法名
        String methodName = requestBean.getMethodName();
        Method method = TypeUtils.getMethodForGettingInstance(resultClass, methodName, paramTypes);
        mMethod = method;
    }
}
